<?php

class CommonAction extends Action {

    function _initialize() {
        import('@.ORG.Util.Cookie');
        // 用户权限检查
        if (C('USER_AUTH_ON') && !in_array(MODULE_NAME, explode(',', C('NOT_AUTH_MODULE')))) {
            import('@.ORG.Util.RBAC');
            if (!RBAC::AccessDecision()) {
                //检查认证识别号
                if (!$_SESSION [C('USER_AUTH_KEY')]) {
                    //跳转到认证网关
                    redirect(PHP_FILE . C('USER_AUTH_GATEWAY'));
                }
                // 没有权限 抛出错误
                if (C('RBAC_ERROR_PAGE')) {
                    // 定义权限错误页面
                    redirect(C('RBAC_ERROR_PAGE'));
                } else {
                    if (C('GUEST_AUTH_ON')) {
                        $this->assign('jumpUrl', PHP_FILE . C('USER_AUTH_GATEWAY'));
                    }
                    // 提示错误信息
                    $this->error(L('_VALID_ACCESS_'));
                }
            }
        }
    }

    public function index() {
        //列表过滤器，生成查询Map对象
        $map = $this->_search();
        if (method_exists($this, '_filter')) {
            $this->_filter($map);
        }
        $name = $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            $this->_list($model, $map);
        }
        $this->display();
        return;
    }

    /**
      +----------------------------------------------------------
     * 取得操作成功后要返回的URL地址
     * 默认返回当前模块的默认操作
     * 可以在action控制器中重载
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @return string
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    function getReturnUrl() {
        return __URL__ . '?' . C('VAR_MODULE') . '=' . MODULE_NAME . '&' . C('VAR_ACTION') . '=' . C('DEFAULT_ACTION');
    }

    /**
      +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
      +----------------------------------------------------------
     * @access protected
      +----------------------------------------------------------
     * @param string $name 数据对象名称
      +----------------------------------------------------------
     * @return HashMap
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    protected function _search($name = '') {
        //生成查询条件
        if (empty($name)) {
            $name = $this->getActionName();
        }
        $name = $this->getActionName();
        $model = D($name);
        $map = array();
        foreach ($model->getDbFields() as $key => $val) {
            if (isset($_REQUEST [$val]) && $_REQUEST [$val] != '') {
                $map [$val] = $_REQUEST [$val];
            }
        }
        return $map;
    }

    /**
      +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
      +----------------------------------------------------------
     * @access protected
      +----------------------------------------------------------
     * @param Model $model 数据对象
     * @param HashMap $map 过滤条件
     * @param string $sortBy 排序
     * @param boolean $asc 是否正序
      +----------------------------------------------------------
     * @return void
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    protected function _list($model, $map, $sortBy = '', $asc = false) {
        //排序字段 默认为主键名
        if (isset($_REQUEST ['_order'])) {
            $order = $_REQUEST ['_order'];
        } else {
			// //echo($this->getActionName());
			// if(strpos(",School,Bdc,Aqxx,St,Zzwy,Nh,",$this->getActionName())){
			// 	 $order = !empty($sortBy) ? $sortBy : 'sortid,id';//$model->getPk();
			// }else{
			// 	 $order = !empty($sortBy) ? $sortBy : $model->getPk();	
			// }          
            $order = !empty($sortBy) ? $sortBy : $model->getPk();   
        }
        //排序方式默认按照倒序排列
        //接受 sost参数 0 表示倒序 非0都 表示正序
        if (isset($_REQUEST ['_sort'])) {
            $sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
        } else {
            if(strpos(",School,Bdc,Aqxx,St,Zzwy,Nh,",$this->getActionName())){
                $sort = $asc ? 'desc' : 'asc';
            }else{
                $sort = $asc ? 'asc'  : 'desc';
            }
            
        }
		/*if (isset($_REQUEST ['_sort'])) {
            $sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
        } else {
            $sort = $asc ? 'asc' : 'desc';
        }*/
        //取得满足条件的记录数
        $count = $model->where($map)->count('id');
        if ($count > 0) {
            import("ORG.Util.Page");
            //创建分页对象
            if (!empty($_REQUEST ['listRows'])) {
                $listRows = $_REQUEST ['listRows'];
            } else {
                $listRows = '';
            }
            $p = new Page($count, $listRows);
            //分页查询数据
			
			//$voList = $model->where($map)->order("`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
            $voList = $model->where($map)->order(" " . $order . " " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
            //echo $model->getlastsql();
            //分页跳转的时候保证查询条件
            foreach ($map as $key => $val) {
                if (!is_array($val)) {
                    $p->parameter .= "$key=" . urlencode($val) . "&";
                }
            }
            //分页显示
            $page = $p->show();
            //列表排序显示
            $sortImg = $sort; //排序图标
            $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
            $sort = $sort == 'desc' ? 1 : 0; //排序方式
            //模板赋值显示
            $this->assign('list', $voList);
            $this->assign('sort', $sort);
            $this->assign('order', $order);
            $this->assign('sortImg', $sortImg);
            $this->assign('sortType', $sortAlt);
            $this->assign("page", $page);
        }
        Cookie::set('_currentUrl_', __SELF__);
        return;
    }

    function insert() {
        //B('FilterString');
        if(!$_SESSION[C('USER_AUTH_KEY')]){
            $this->error('请先登录!',true);
            return;
        }
        $name = $this->getActionName();
        $model = D($name);
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        //保存当前数据对象
        $list = $model->add();
        if (false !== $list) {
            //成功提示
            $this->assign('jumpUrl', Cookie::get('_currentUrl_'));
            $this->success('新增成功!',true);
        } else {
            //错误提示
           $this->error('新增失败!',true);
        }
    }

    public function add() {
        $this->display();
    }

    function read() {
        $this->edit();
    }

    function edit() {
        $name = $this->getActionName();
        $model = M($name);
        $id = $_REQUEST [$model->getPk()];
		//$id = 0==$_SESSION['dwid']?$_REQUEST[$model->getPk()]:$_SESSION['dwid'];
        $vo = $model->getById($id);
        $this->assign('vo', $vo);
        $this->display();
    }

    function editAjax() {
        $name = $this->getActionName();
        $model = M($name);
        $id = $_REQUEST [$model->getPk()];
        //$id = 0==$_SESSION['dwid']?$_REQUEST[$model->getPk()]:$_SESSION['dwid'];
        $vo = $model->getById($id);
        echo json_encode($vo);   
    }

    function update() {
        //B('FilterString');
        $name = $this->getActionName();
        $model = D($name);
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        // 更新数据
        $list = $model->save();
        if (false !== $list) {
            //成功提示
            $this->assign('jumpUrl', Cookie::get('_currentUrl_'));
            $this->success('编辑成功!',true);
        } else {
            //错误提示
           $this->error('编辑失败1!',true);
        }
    }

    /**
      +----------------------------------------------------------
     * 默认删除操作
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @return string
      +----------------------------------------------------------
     * @throws ThinkExecption
      +----------------------------------------------------------
     */
    public function delete() {
        //删除指定记录
        $name = $this->getActionName();
        $model = M($name);
        if (!empty($model)) {
            $pk = $model->getPk();
            $id = $_REQUEST [$pk];
            if (isset($id)) {
                $condition = array($pk => array('in', explode(',', $id)));
                $list = $model->where($condition)->setField('status', - 1);
                if ($list !== false) {
                    $this->success('删除成功！');
                } else {
                    $this->error('删除失败！');
                }
            } else {
                $this->error('非法操作');
            }
        }
    }

    public function foreverdelete() {
        //删除指定记录
        $name = $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            $pk = $model->getPk();
            $id = $_REQUEST [$pk];
            if (isset($id)) {
                $condition = array($pk => array('in', explode(',', $id)));
                if (false !== $model->where($condition)->delete()) {
                    $this->success('删除成功！',true);
                } else {
                    $this->error('删除失败！',false);
                }
            } else {
                $this->error('非法操作',false);
            }
        }
        //echo $model->getlastsql();
        //trace('最后语句',$model->getlastsql());
        $this->forward();
    }

    //删除自己userid的记录
    public function delSelf(){
        $name = $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            $pk = $model->getPk();
            $id = $_REQUEST [$pk];
            if (isset($id)) {
                $condition = array($pk => array('in', explode(',', $id)));
                $condition['userid'] = $_SESSION[C('USER_AUTH_KEY')];
                if ($model->where($condition)->delete() > 0) {
                    $this->success('删除成功！',true);
                } else {
                    $this->error('删除失败！',false);
                }
            } else {
                $this->error('非法操作',false);
            }
        }
        $this->forward();
    }
	
	public function lockAll(){
		$name = $this->getActionName();
        $model = D($name);
		if (!empty($model)) {
			if (false !== $model->where("dwid>0")->setField('status',$_POST['status'])) {
				//echo $model->getlastsql();
				$this->success('锁定成功！',true);
			} else {
				$this->error('锁定失败！',false);
			}
		} else {
			$this->error('非法操作',false);
		}
        $this->forward();	
	}

    public function clear() {
        //删除指定记录
        $name = $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            if (false !== $model->where('status=1')->delete()) {
                $this->assign("jumpUrl", $this->getReturnUrl());
                $this->success(L('_DELETE_SUCCESS_'));
            } else {
                $this->error(L('_DELETE_FAIL_'));
            }
        }
        $this->forward();
    }

    /**
      +----------------------------------------------------------
     * 默认禁用操作
     *
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @return string
      +----------------------------------------------------------
     * @throws FcsException
      +----------------------------------------------------------
     */
    public function forbid() {
        $name = $this->getActionName();
        $model = D($name);
        $pk = $model->getPk();
        $id = $_REQUEST [$pk];
        $condition = array($pk => array('in', $id));
        $list = $model->forbid($condition);
        if ($list !== false) {
            $this->assign("jumpUrl", $this->getReturnUrl());
            $this->success('状态禁用成功');
        } else {
            $this->error('状态禁用失败！');
        }
    }

    public function checkPass() {
        $name = $this->getActionName();
        $model = D($name);
        $pk = $model->getPk();
        $id = $_GET [$pk];
        $condition = array($pk => array('in', $id));
        if (false !== $model->checkPass($condition)) {
            $this->assign("jumpUrl", $this->getReturnUrl());
            $this->success('状态批准成功！');
        } else {
            $this->error('状态批准失败！');
        }
    }

    public function recycle() {
        $name = $this->getActionName();
        $model = D($name);
        $pk = $model->getPk();
        $id = $_GET [$pk];
        $condition = array($pk => array('in', $id));
        if (false !== $model->recycle($condition)) {

            $this->assign("jumpUrl", $this->getReturnUrl());
            $this->success('状态还原成功！');
        } else {
            $this->error('状态还原失败！');
        }
    }

    public function recycleBin() {
        $map = $this->_search();
        $map ['status'] = - 1;
        $name = $this->getActionName();
        $model = D($name);
        if (!empty($model)) {
            $this->_list($model, $map);
        }
        $this->display();
    }

    /**
      +----------------------------------------------------------
     * 默认恢复操作
     *
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @return string
      +----------------------------------------------------------
     * @throws FcsException
      +----------------------------------------------------------
     */
    function resume() {
        //恢复指定记录
        $name = $this->getActionName();
        $model = D($name);
        $pk = $model->getPk();
        $id = $_GET [$pk];
        $condition = array($pk => array('in', $id));
        if (false !== $model->resume($condition)) {
            $this->assign("jumpUrl", $this->getReturnUrl());
            $this->success('状态恢复成功！');
        } else {
            $this->error('状态恢复失败！');
        }
    }

    function saveSort() {
        $seqNoList = $_POST ['seqNoList'];
        if (!empty($seqNoList)) {
            //更新数据对象
            $name = $this->getActionName();
            $model = D($name);
            $col = explode(',', $seqNoList);
            //启动事务
            $model->startTrans();
            foreach ($col as $val) {
                $val = explode(':', $val);
                $model->id = $val [0];
                $model->sort = $val [1];
                $result = $model->save();
                if (!$result) {
                    break;
                }
            }
            //提交事务
            $model->commit();
            if ($result !== false) {
                //采用普通方式跳转刷新页面
                $this->success('更新成功');
            } else {
                $this->error($model->getError());
            }
        }
    }

    //查看用户模块权限
    function checkModelAccess($model){
        $array = RBAC::getAccessList($_SESSION[C('USER_AUTH_KEY')]);
        if(C('USER_AUTH_ON') && array_key_exists($model,$array['HQGLHOME'])){
            return true;
        }else{
            return false;   
        }
    }
	
	//myread，读取某一条记录，并ajax返回数据
	public function myRead() {
        $name 	= $this->getActionName();
        $model 	= D($name);
		$list	= $model->find($_REQUEST['id']); 
        if (!empty($model)) {
            $this->ajaxReturn($list);
        }
        return;
    }
    //结合easyUI的Datagrid输出相应的json数据
    public function gridRead(){
        $pagenum= isset($_POST['page']) ? intval($_POST['page']) : 1;
        $rowsnum= isset($_POST['rows']) ? intval($_POST['rows']) : 10;
        //$name   = $this->getActionName();
        $name   = $_POST['actionName']?$_POST['actionName']:$this->getActionName();
        $model  = D($name);

        $total  = $model->count();    //计算总数 
        $list   = array();
            
        $list   = $model->limit(($pagenum-1)*$rowsnum.','.$rowsnum)->order('id asc')->select();
        $json   = '{"total":'.$total.',"rows":'.json_encode($list).'}';//重要，easyui的标准数据格式，数据总数和数据内容在同一个json中
        echo $json;
    }
	//查看某个详细字段，最初是用于效果图，平面图，传入id,和要读取的字段名
	function myGetField(){
		$name 	= $_POST['actionName']?$_POST['actionName']:$this->getActionName();
        $model 	= D($name);
		$id		= $_POST['id'];
		$f		= $_POST['f']?$_POST['f']:"remarks"; //默认查询备注字段
		$ff		= $model->where('id='.$id)->getField($f);
		//echo $model->getLastSql(); 
		if($ff){
			$this->ajaxReturn($ff,"查询成功！",1); 
		}else{
		  	$this->ajaxReturn('无信息',"没有相关信息！",0); 
		}
	}
	
    //读取电子表格到数组
    function excelToArray1($file){
        $objReader = PHPExcel_IOFactory::createReader('Excel5');  
        $objReader->setReadDataOnly(true);  
        $objPHPExcel = $objReader->load($file);  
        $objWorksheet = $objPHPExcel->getActiveSheet();  
        $highestRow = $objWorksheet->getHighestRow();   
        $highestColumn = $objWorksheet->getHighestColumn();   
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);  
        $excelData = array();  
        for ($row = 2; $row <= $highestRow; ++$row) {  
            for ($col = 0; $col <= $highestColumnIndex; ++$col) {  
                $excelData[$row][] = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();  
            }  
        }  
        return $excelData;  
    } 
	//导出数据到excel///////////////////////////////////////////////////
	function saveExcel(){  
        if(strpos("-,毕东宁,吴希华,-",','.$_SESSION['loginUserName'].',')<1){
            return;
        }
		$title			= $_GET['title'];//显示的标题，文件名，sheet名字
		//$title			= iconv("utf-8","gb2312",urldecode($_GET['title']));//显示的标题，文件名，sheet名字
		$eType			= $_GET['eType'];//文件类型，Excel5或者Excel2007
		$fType1			= $eType=='Excel2007'?'.xlsx':'.xls';//由文件类型选择不同的文件扩展名
		$fieldString	= $_GET['fieldString'];//要读取的字段列表
		$titleString	= $_GET['titleString'];//各字段的标题显示名
		
		$bl				= $_GET['bl'];//开始显示数据的行呈，默认第三行，第一行标题，第二行字段名beginLine
		
		$fieldArray 	= explode(",", $fieldString);//字段数组
		$titleArray		= explode(",", $titleString);//标题数组
		$abc			= explode(',',"A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,AA,AB,AC,AD,AE,AF,AG,AH,AI,AJ,AK,AL,AM,AN,AO,AP,AQ,AR,AS,AT,AU,AV,AW,AX,AY,AZ,BA,BB,BC,BD,BE,BF,BG,BH,BI,BJ,BK,BL");
				
		$name 			= $_GET['model'];//模块名，也就是数据库名或者是视图名
        $model 			= D($name);


        vendor("PHPExcel176.PHPExcel");  
        // Create new PHPExcel object  
        $objPHPExcel = new PHPExcel();  //这个不用也可以，是不是高效一些？
        if($eType=='Excel2007')
            $objReader      = new PHPExcel_Reader_Excel2007();
        else
            $objReader      = new PHPExcel_Reader_Excel5();
        $objPHPExcel    = $objReader->load(C('upload_Path').'/excelExample/'.$name.$fType1);//读取各模块相应的源excel文件，从新生成太麻烦了，还是直接读取快
       
        // Set properties  
        $objPHPExcel->getProperties()->setCreator("ctos")  
            ->setLastModifiedBy("ZHXZJY")  
            ->setTitle("ZHXZJY后勤管理系统")  
            ->setSubject("ZHXZJY后勤管理系统")  
            ->setDescription("ZHXZJY后勤管理系统, generated using PHP classes,code by YH")  
            ->setKeywords("office 2007 openxml php")  
            ->setCategory("XZJY");  

		
        if($name=='Weekwa'){
            $Start  = $_SESSION['weekStart'];
            $End    = $_SESSION['weekEnd'];
            $OrdersData = $model->where("riqi>=$Start and riqi <=$End")->order('riqi,sxw')->select(); 
        }else if($name=='Monthwa'){
            $Start  = $_SESSION['monthStart'];
            $End    = $_SESSION['monthEnd'];
            $OrdersData = $model->where("riqi>=$Start and riqi <=$End")->order('riqi,shijian')->select(); 
        }else if($name=='Weeklist'){
            $Start  = $_SESSION['weekStart'];
            $End    = $_SESSION['weekEnd'];
            $bl     = 4;
            $sa3    = toDate($Start,'Y年m月d日').'-'.toDate($End,'Y年m月d日');
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A2',$sa3);
            $OrdersData = $model->where("riqi>=$Start and riqi <=$End")->order('riqi,sort desc')->select(); 
        }
        //echo $model->getLastSql();
        // return;
  
		
  
        // set table header content  
		foreach( $titleArray as $key=>$value){
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($abc[$key].($bl-1),$value);	
		} 
		//  
		$lastNO = $abc[$key];//最后的一个字段到达的字母，如，J,L,等
		$t1 = 'A1:'.$lastNO.'1';//标题行
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1',$title);
        $objPHPExcel->getActiveSheet()->mergeCells($t1); //合并首行，显示标题
		$objPHPExcel->getActiveSheet()->getStyle($t1)->getFont()->setSize(20); //首行字体大小 
        $objPHPExcel->getActiveSheet()->getStyle($t1)->getFont()->setBold(true);  //加粗
		$objPHPExcel->getActiveSheet()->getStyle($t1)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//水平居中  
		
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(12);//a列宽
		
		//set font size bold  
		//$t2 = 'A2:'.$lastNO.'2';//字段行
		$t2 = 'A'.($bl-1).':'.$lastNO.''.($counter+$bl-1);
        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(12);  
        $objPHPExcel->getActiveSheet()->getStyle($t2)->getFont()->setBold(true);  
  
        $objPHPExcel->getActiveSheet()->getStyle($t2)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);  
        $objPHPExcel->getActiveSheet()->getStyle($t2)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN); 

        //设置默认行高
        $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(40);
  
        // 读取数据库数据////////////////////////////////////////////////////////////////////////////////////////////
		$counter = count($OrdersData);
		//日期字段列表
		$dataFieldList  = "-,riqi,-";//日期字段，加入时间戳转换函数
		for($i=0;$i<$counter;$i++){ 
              foreach( $fieldArray as $key=>$value){    
                  if(strpos($dataFieldList,','.$value.',')){
                    //将时间戳转换为日期格式
                    $objPHPExcel->getActiveSheet()->setCellValue($abc[$key].($i+$bl), toDate($OrdersData[$i][$value],'Y-m-d'));
                    //$objPHPExcel->getActiveSheet()->setCellValue($abc[$key].($i+3), PHPExcel_Shared_Date::PHPToExcel($OrdersData[$i][$value]));
                    //$objPHPExcel->getActiveSheet(0)->getStyle($abc[$key].($i+3))->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);   
                  }else
                    $objPHPExcel->getActiveSheet(0)->setCellValue($abc[$key].($i+$bl), strip_tags($OrdersData[$i][$value]));  
              }      
            // 设置行高
            //$objPHPExcel->getActiveSheet()->getRowDimension($i+$bl)->setRowHeight(40);
        }  
  		//set font size bold  
		$t3 = 'A'.$bl.':'.$lastNO.''.($counter+$bl-1);//数据行范围
		
        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(12);    
        $objPHPExcel->getActiveSheet()->getStyle($t3)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);  
        $objPHPExcel->getActiveSheet()->getStyle($t3)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
        
   
        // Rename sheet  
        $objPHPExcel->getActiveSheet()->setTitle($title);  
  
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet  
        $objPHPExcel->setActiveSheetIndex(0);  
        // Redirect output to a client's web browser (Excel5)  
        header('Content-Type: application/vnd.ms-excel');  
        header('Content-Disposition: attachment;filename="'.iconv("utf-8","gb2312",urldecode($_GET['title'])).'('.date('Ymd').')'.$fType1.'"');  
        header('Cache-Control: max-age=0'); 
  
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $eType);  
        $objWriter->save('php://output');  
		exit;
    }  
}

?>